package amit.ui.window;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import amit.ad.AdDetails;
import amit.browser.Browser;
import amit.calc.form.MainForm;
import amit.ui.table.AdComperator;
import amit.ui.table.AdFilterator;
import amit.ui.table.AdTable;
import amit.ui.table.AdTableFormat;
import amit.util.FetchAllAds;
import amit.util.FileUtil;
import amit.util.SwingWorker;
import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.SortedList;
import ca.odell.glazedlists.swing.EventSelectionModel;
import ca.odell.glazedlists.swing.EventTableModel;
import ca.odell.glazedlists.swing.TableComparatorChooser;
import ca.odell.glazedlists.swing.TextComponentMatcherEditor;

/**
 * The main frame of the app.
 * Hold the scanner tab and the calculator tab
 * @author ido
 * 
 */
public class AmitMainFrame extends javax.swing.JFrame {

	public final static int ONE_SECOND = 1000;
	public final static int MAX_TIME_TO_WAIT_FOR_SCAN_THREAD = Integer
			.parseInt(System.getProperty("max.time.out.for.scan.thread",
					"600000"));
	private JTabbedPane tabPane;
	
	private AdTable rentAdTable;
	private AdTable saleAdTable;
	private ArrayList<AdDetails> rentAds;
	private ArrayList<AdDetails> saleAds;
	private EventList adRentEventList;
	private EventList adSaleEventList;
	private JPanel scanerMainPanel;
	private JPanel rentPanel, salePanel, bottomPanel;
	private JTextField rentFilter, saleFilter;
	private Browser saleRentBrowser; //rentBrowser

	private JProgressBar scanProgress;
	private Timer timer;

	private FetchAllAds adsFetcher;

	private JMenuItem deleteMenuItem;
	private JSeparator jSeparator1;
	private JMenuItem pasteMenuItem;
	private JMenuItem copyMenuItem;
	private JMenuItem cutMenuItem;
	private JMenu editMenu;
	private JMenuItem exitMenuItem;
	private JSeparator jSeparator2;
	private JMenuItem exportMenuItem;

	private JMenu fileMenu;
	private JMenuItem scanMenuItem;
	private JMenuItem refreshMenuItem;
	private JMenuBar mainMenuBar;

	private JMenuItem helpMenuItem;
	private JMenu helpMenu;

	public AmitMainFrame() {
		super();
		initGUI();
	}

	private void fetchAds() {
		adsFetcher = new FetchAllAds();
		timer.start();
		final SwingWorker worker = new SwingWorker() {
			public Object construct() {
				adsFetcher.runOnAllRent();
				adsFetcher.runOnAllSale();
				return adsFetcher;
			}
		};
		worker.start();

		final SwingWorker check_active_threads = new SwingWorker() {
			public Object construct() {
				try {
					Thread.sleep(20000);
					while (FetchAllAds.number_of_running_scan_threads > 0) {
						System.out.println("checking threads numbers... "+FetchAllAds.number_of_running_scan_threads);
						Thread.sleep(3000);
					}
					System.out.println(" NO more running scan threads! so update the UI");
					readData();
					createTable();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		};
		check_active_threads.start();
	}

	private void buildMenu() {
		mainMenuBar = new JMenuBar();
		setJMenuBar(mainMenuBar);
		fileMenu = new JMenu();
		mainMenuBar.add(fileMenu);
		fileMenu.setText("File");
		scanMenuItem = new JMenuItem("Scan Ads");
		scanMenuItem.setMnemonic('S');
		scanMenuItem.setAccelerator(KeyStroke.getKeyStroke(
		        KeyEvent.VK_S, ActionEvent.ALT_MASK));
		fileMenu.add(scanMenuItem);
		scanMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				fetchAds();
			}
		});
		refreshMenuItem = new JMenuItem("Refresh Ads");
		refreshMenuItem.setMnemonic('R');
		refreshMenuItem.setAccelerator(KeyStroke.getKeyStroke(
		        KeyEvent.VK_R, ActionEvent.ALT_MASK));
		fileMenu.add(refreshMenuItem);
		refreshMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				readData();
				createTable();
			}
		});
		exportMenuItem = new JMenuItem("Export");
		exportMenuItem.setMnemonic('E');
		fileMenu.add(exportMenuItem);

		jSeparator2 = new JSeparator();
		fileMenu.add(jSeparator2);
		exitMenuItem = new JMenuItem("Exit");
		exitMenuItem.setMnemonic('x');
		exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(
		        KeyEvent.VK_F4, ActionEvent.ALT_MASK));
		fileMenu.add(exitMenuItem);
		exitMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});

		editMenu = new JMenu("Edit");
		mainMenuBar.add(editMenu);
		editMenu.setText("Edit");
		cutMenuItem = new JMenuItem();
		editMenu.add(cutMenuItem);
		cutMenuItem.setText("Cut");
		copyMenuItem = new JMenuItem();
		editMenu.add(copyMenuItem);
		copyMenuItem.setText("Copy");
		pasteMenuItem = new JMenuItem();
		editMenu.add(pasteMenuItem);
		pasteMenuItem.setText("Paste");
		jSeparator1 = new JSeparator();
		editMenu.add(jSeparator1);
		deleteMenuItem = new JMenuItem();
		editMenu.add(deleteMenuItem);
		deleteMenuItem.setText("Delete");
		helpMenu = new JMenu("Help");
		mainMenuBar.add(helpMenu);
		helpMenuItem = new JMenuItem("Help");
		helpMenu.add(helpMenuItem);
		helpMenuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(AmitMainFrame.this,
						"+Cash Researcher\nVersion: 0.3\nScans for: Dira, Bait\nCalc version: 0.1", "+Cash Researcher",
						JOptionPane.INFORMATION_MESSAGE);

			}

		});
		/*
		 * JMenu testColor = new JMenu("test color"); testColor.add(new
		 * JMenuItem(new
		 * ImageIcon("C:\\eclipse3-2\\workspace\\AmitRent\\etc\\red.GIF")));
		 * testColor.add(new JMenuItem(new
		 * ImageIcon("C:\\eclipse3-2\\workspace\\AmitRent\\etc\\blue.GIF")));
		 * testColor.add(new JMenuItem(new
		 * ImageIcon("C:\\eclipse3-2\\workspace\\AmitRent\\etc\\yellow.GIF")));
		 * helpMenu.add(testColor);
		 */
	}

	private void loadSaleAd() {
		EventList<AdDetails> selectedRow = ((EventSelectionModel) saleAdTable
				.getSelectionModel()).getSelected();
		System.out.println(" The Selected SALE ad:" + selectedRow.get(0));
		saleRentBrowser.loadUrl(selectedRow.get(0).getSaleUrlId());

	}

	private void loadRentAd() {
		EventList<AdDetails> selectedRow = ((EventSelectionModel) rentAdTable
				.getSelectionModel()).getSelected();
		System.out.println(" The Selected RENT ad:" + selectedRow.get(0));
		saleRentBrowser.loadUrl(selectedRow.get(0).getRentUrlId());
	}

	private void createTable() {
		try {
			SortedList sortedAds = new SortedList(adRentEventList,
					new AdComperator());

			rentFilter = new JTextField(15);
			FilterList rentAdFiltered = new FilterList(sortedAds,
					new TextComponentMatcherEditor(rentFilter,
							new AdFilterator()));

			EventTableModel adTableModel = new EventTableModel(rentAdFiltered,
					new AdTableFormat());
			rentAdTable = new AdTable(adTableModel);

			EventSelectionModel adRentEventSelectionModel = new EventSelectionModel(
					rentAdFiltered);
			rentAdTable.setSelectionModel(adRentEventSelectionModel);
			rentAdTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			// Ask to be notified of selection changes.
			ListSelectionModel rowSM = rentAdTable.getSelectionModel();
			rowSM.addListSelectionListener(new ListSelectionListener() {
				public void valueChanged(ListSelectionEvent e) {
					// Ignore extra messages.
					if (e.getValueIsAdjusting())
						return;

					ListSelectionModel lsm = (ListSelectionModel) e.getSource();
					if (!lsm.isSelectionEmpty()) {
						// int selectedRow = lsm.getMinSelectionIndex();
						loadRentAd();
					}
				}
			});

			TableComparatorChooser tableSorter = new TableComparatorChooser(
					rentAdTable, sortedAds, true);

			JScrollPane rentPane = new JScrollPane(rentAdTable);
			rentPanel.removeAll();
			JPanel topRentPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
			topRentPanel.add(new JLabel("Filter:"));
			topRentPanel.add(rentFilter);
			rentPanel.add(topRentPanel, BorderLayout.NORTH);
			rentPanel.add(rentPane, BorderLayout.CENTER);
			rentPanel.add(new JLabel("Number of Rent Ads: " + rentAds.size()),
					BorderLayout.SOUTH);
			rentPanel.setBorder(BorderFactory.createTitledBorder(" Rent App "));

			//
			// and now the sale table
			//
			SortedList sortedSaleAds = new SortedList(adSaleEventList,
					new AdComperator());
			saleFilter = new JTextField(15);
			FilterList saleAdFiltered = new FilterList(sortedSaleAds,
					new TextComponentMatcherEditor(saleFilter,
							new AdFilterator()));

			EventTableModel saleAdTableModel = new EventTableModel(
					saleAdFiltered, new AdTableFormat());
			saleAdTable = new AdTable(saleAdTableModel);

			EventSelectionModel adSaleEventSelectionModel = new EventSelectionModel(
					saleAdFiltered);
			saleAdTable.setSelectionModel(adSaleEventSelectionModel);
			saleAdTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			// Ask to be notified of selection changes.
			ListSelectionModel rowSMsale = saleAdTable.getSelectionModel();
			rowSMsale.addListSelectionListener(new ListSelectionListener() {
				public void valueChanged(ListSelectionEvent e) {
					// Ignore extra messages.
					if (e.getValueIsAdjusting())
						return;

					ListSelectionModel lsm = (ListSelectionModel) e.getSource();
					if (!lsm.isSelectionEmpty()) {
						// int selectedRow = lsm.getMinSelectionIndex();
						loadSaleAd();
					}
				}
			});

			// saleAdTable.setLocale(new Locale("he"));
			TableComparatorChooser saleTableSorter = new TableComparatorChooser(
					saleAdTable, sortedSaleAds, true);

			JScrollPane salePane = new JScrollPane(saleAdTable);

			JPanel topSalePanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
			topSalePanel.add(new JLabel("Filter:"));
			topSalePanel.add(saleFilter);
			salePanel.removeAll();
			salePanel.add(topSalePanel, BorderLayout.NORTH);
			salePanel.add(salePane, BorderLayout.CENTER);
			salePanel.add(new JLabel("Number of Sale Ads: " + saleAds.size()),
					BorderLayout.SOUTH);
			salePanel.setBorder(BorderFactory.createTitledBorder(" Sale App "));
			repaint();
			pack();
			scanProgress.setString("Ads are fresh");

		} catch (Exception e) {
			System.err.println("Could not build the tables");
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @throws Exception
	 */
	private void readData() {
		try {
			rentAds = new ArrayList<AdDetails>();
			saleAds = new ArrayList<AdDetails>();
			File dir = new File(FileUtil.DATA_DIR);
			String[] fileNames = dir.list();
			for (int i = 0; i < fileNames.length; i++) {
				if (fileNames[i].indexOf("_rent") > 0) {
					System.out.println("read into rent:" + fileNames[i]);
					rentAds.addAll(FileUtil.sharedInstance
							.readAdFile(FileUtil.DATA_DIR + fileNames[i]));
				} else if (fileNames[i].indexOf("_sale") > 0) {
					System.out.println("read into sale:" + fileNames[i]);
					saleAds.addAll(FileUtil.sharedInstance
							.readAdFile(FileUtil.DATA_DIR + fileNames[i]));
				} else {
					System.out.println("did NOT insert file:" + fileNames[i]);

				}
			}
			adRentEventList = new BasicEventList();
			adRentEventList.addAll(rentAds);

			adSaleEventList = new BasicEventList();
			adSaleEventList.addAll(saleAds);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void createBottomPanel() {
		bottomPanel = new JPanel(new BorderLayout(12, 12));
		scanProgress = new JProgressBar(0, FetchAllAds.NO_AREA);
		scanProgress.setStringPainted(true);
		bottomPanel.add(scanProgress, BorderLayout.SOUTH);
		timer = new Timer(ONE_SECOND, new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				// System.out.println("#######
				// dsFetcher.getNoOfFiles():"+adsFetcher.getNoOfFiles());
				scanProgress.setValue(adsFetcher.getNoOfFiles());
				if (adsFetcher.isDone()) {
					Toolkit.getDefaultToolkit().beep();
					timer.stop();
					scanProgress.setString("Refreshed the Ads");
				}
			}
		});

		// browsers
		// JPanel bPanel = new JPanel();
		// BoxLayout boxLayout = new BoxLayout(bPanel , BoxLayout.X_AXIS);
		// bPanel.setLayout(boxLayout);
		
		//rentBrowser = new Browser();
		//rentBrowser.setMinimumSize(new Dimension(10, 10));
		//rentBrowser.setPreferredSize(new Dimension(400, 300));
		//rentBrowser.loadUrl("http://www.homeless.co.il/rent/");

		saleRentBrowser = new Browser();
		saleRentBrowser.setPreferredSize(new Dimension(400, 300));
		saleRentBrowser.setMinimumSize(new Dimension(10, 10));
		// saleRentBrowser.loadUrl("http://www.homeless.co.il/sale/");
		// bPanel.add(saleRentBrowser);
		//JSplitPane spBrowsers = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,		saleRentBrowser, rentBrowser);
		//spBrowsers.setOneTouchExpandable(true);
		bottomPanel.add(saleRentBrowser, BorderLayout.CENTER);
	}

	/**
	 * 
	 * 
	 */
	private void initGUI() {
		try {
			javax.swing.UIManager
					.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
			setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
			scanerMainPanel = new JPanel();
			BoxLayout boxLayout = new BoxLayout(scanerMainPanel, BoxLayout.X_AXIS);
			scanerMainPanel.setLayout(boxLayout); 
			rentPanel = new JPanel(new BorderLayout(12, 12));
			salePanel = new JPanel(new BorderLayout(12, 12));
			createBottomPanel();
			readData();
			createTable();
			scanerMainPanel.add(salePanel);
			scanerMainPanel.add(rentPanel);
			
			getContentPane().setLayout(new BorderLayout(12, 12));
			JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
					scanerMainPanel, bottomPanel);
			sp.setOneTouchExpandable(true);
			
			tabPane = new JTabbedPane();
			tabPane.add("Calculator",new MainForm());
			tabPane.add("Ads", sp);
			
			getContentPane().add(tabPane, BorderLayout.CENTER);
			// getContentPane().add(bottomPanel, BorderLayout.SOUTH);

			buildMenu();
			setTitle("+Cash Researcher");
			pack();
			setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	public static void main(String[] args) throws Exception {
		AmitMainFrame inst = new AmitMainFrame();
		inst.setVisible(true);
	}

}
